package com.contactbook.web.client;

import com.contactbook.web.client.dto.GroupDTO;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class AddGroupWidget extends View {
	
	private static enum Mode {CREATE, UPDATE};
	
	private Mode mode;
	
	private TextBox textBoxName;
	private TextArea textAreaDescription;
	private Label labelInfo;
	
	private int groupToUpdateId = 0;
	
	/* Properties */
	private static final String NAME_TEXTBOX_SIZE = "180px";
	private static final String DESCRIPTION_TEXTAREA_HEIGHT_SIZE = "120px"; 
	private static final String DESCRIPTION_TEXTAREA_WIDTH_SIZE = "200px"; 
	
	private static final String TITLE_CREATE = "Create a new group of contacts";
	private static final String TITLE_UPDATE = "Update a group";
	
	private VerticalPanel content;
	
	public AddGroupWidget(ContactBook contactBook) {

		super(contactBook);

	}
	
	private class CancelHandler implements ClickHandler {
		public void onClick(ClickEvent event) {
			contactBook.switchView(Constants.ListOfContactsViewName);
		}
	}
	
	private class ClickAddHandler implements ClickHandler {
		
		public void onClick(ClickEvent event) {
			String name = textBoxName.getText();
			String description = textAreaDescription.getText();
			
			if (!name.isEmpty()) {
						
				AsyncCallback<GroupDTO> callbackAdd = new AsyncCallback<GroupDTO>() {

					@SuppressWarnings("deprecation")
					@Override
					public void onFailure(Throwable caught) {
						content.clear();
						content.add(new ErrorPanel());						
					}

					@Override
					public void onSuccess(GroupDTO result) {
						DialogBoxWidget dialog = new DialogBoxWidget(contactBook, "The group '" + result.getName() + "' has been created in your contact book");
						dialog.onHide("listOfContacts");					
					}					
				};
				
				GroupDTO groupDTOCreated = new GroupDTO();
				groupDTOCreated.setName(name);
				groupDTOCreated.setDescription(description);
				groupDTOCreated.setAccount(contactBook.getCurrentSession().getAccountLogged());				
				contactBook.getGroupService().add(groupDTOCreated, contactBook.getCurrentSession().getLogin(), contactBook.getCurrentSession().getPassword(), callbackAdd);
			} else {
				new DialogBoxWidget(contactBook, "Please give at least a name");
			}
		}
	}
	
	private class ClickUpdateHandler implements ClickHandler {
		
		private int groupId;
		public ClickUpdateHandler(int groupId) {
			this.groupId = groupId;
		}
		
		@Override
		public void onClick(ClickEvent arg0) {
			updateGroup(groupId);
		}
	}

	@Override
	public VerticalPanel getContent() {
		if (contactBook.isLogged()) {
			clearContent();
			if (contactBook.getCurrentSession().parameters.get(Constants.SessionParameterGroupId) != null) {
				mode = Mode.UPDATE;
				groupToUpdateId = (Integer)contactBook.getCurrentSession().parameters.get(Constants.SessionParameterGroupId);
				contactBook.getCurrentSession().parameters.remove(Constants.SessionParameterGroupId);
			} else
				mode = Mode.CREATE;
			buildView();
			return content;
		} else
			contactBook.switchView(Constants.LoginViewName);
		return null;
	}
	
	public VerticalPanel buildView() {
		
		content = new VerticalPanel();
		
		DecoratorPanel panelAddGroup = new DecoratorPanel();
		VerticalPanel panelWidgets = new VerticalPanel();
		panelWidgets.setWidth(Constants.SmallPanelWidgetsStandartWidth);
		panelWidgets.setSpacing(5);

		labelInfo = new Label();
		labelInfo.setStyleName("gwt-label-labelnote");
		if (mode == Mode.CREATE)
			labelInfo.setText("Create a group of contacts");
		
		FlexTable table = new FlexTable();
		
		final Label labelName = new Label("Name :");
		textBoxName = new TextBox();
		textBoxName.setWidth(NAME_TEXTBOX_SIZE);
		textBoxName.setFocus(true);
		
		table.setWidget(0, 0, labelName);
		table.setWidget(0, 1, textBoxName);
		
		final Label labelDescription = new Label("Description :");
		textAreaDescription = new TextArea();
		textAreaDescription.setHeight(DESCRIPTION_TEXTAREA_HEIGHT_SIZE);
		textAreaDescription.setWidth(DESCRIPTION_TEXTAREA_WIDTH_SIZE);
		
		table.setWidget(1, 0, labelDescription);
		table.setWidget(1, 1, textAreaDescription);
			
		final Button buttonOk = new Button("Ok");
		
		if (mode == Mode.CREATE)
			buttonOk.addClickHandler(new ClickAddHandler());
		else {
			buttonOk.addClickHandler(new ClickUpdateHandler(groupToUpdateId));
			loadGroup();
		}
		buttonOk.setStyleName("buttonform");
		
		final Button buttonCancel = new Button("Cancel");
		buttonCancel.addClickHandler(new CancelHandler());
		buttonCancel.setStyleName("buttonform");
		
		table.setWidget(2, 0, buttonOk);
		table.setWidget(2, 1, buttonCancel);
		
		/* Table properties */
		table.getFlexCellFormatter().setHeight(2, 0, "50px");
		
		table.getFlexCellFormatter().setAlignment(2, 0, ALIGN_CENTER, ALIGN_MIDDLE);
		table.getFlexCellFormatter().setAlignment(2, 1, ALIGN_CENTER, ALIGN_MIDDLE);
		
		table.setCellPadding(8);
		
		panelWidgets.add(labelInfo);
		panelWidgets.add(table);
		
		panelAddGroup.add(panelWidgets);

		content.add(panelAddGroup);
				
		return content;
	}
	
	private void updateGroup(int groupId) {
		final AsyncCallback<Void> callbackUpdate = new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable arg0) {
			}

			@Override
			public void onSuccess(Void arg0) {
				contactBook.switchView(Constants.ListOfContactsViewName);
			}			
		};
		AsyncCallback<GroupDTO> callbackGetGroup = new AsyncCallback<GroupDTO>() {

			@SuppressWarnings("deprecation")
			@Override
			public void onFailure(Throwable caught) {
				content.clear();
				content.add(new ErrorPanel());								
			}

			@Override
			public void onSuccess(GroupDTO result) {
				result.setName(textBoxName.getText());
				if (!textAreaDescription.getText().isEmpty())
					result.setDescription(textAreaDescription.getText());
				contactBook.getGroupService().update(result, contactBook.getCurrentSession().getLogin(), contactBook.getCurrentSession().getPassword(), callbackUpdate);
			}
		};
		contactBook.getGroupService().getGroupById(groupId, contactBook.getCurrentSession().getLogin(), contactBook.getCurrentSession().getPassword(), callbackGetGroup);
	}
	
	public void loadGroup() {
		AsyncCallback<GroupDTO> callback = new AsyncCallback<GroupDTO>() {

			@Override
			public void onFailure(Throwable arg0) {}

			@Override
			public void onSuccess(GroupDTO result) {
				textBoxName.setText(result.getName());
				textAreaDescription.setText(result.getDescription());
				labelInfo.setText("Update the group '" + result.getName() + "'");
			}			
		};
		contactBook.getGroupService().getGroupById(groupToUpdateId, contactBook.getCurrentSession().getLogin(), contactBook.getCurrentSession().getPassword(), callback);
	}

	@Override
	public String getTitle() {
		if (mode == Mode.CREATE)
			return TITLE_CREATE;
		return TITLE_UPDATE;
	}
	
	private void clearContent() {
		if (content != null) {
			content.clear();
			textBoxName.setText("");
			textAreaDescription.setText("");
		}
	}
}
